//
//  UIView+KSShow.m
//  KSBridgeDesign
//
//  Created by huzhaoke on 2021/4/5.
//

#import "UIView+KSShow.h"
#import <BlocksKit/NSObject+BKBlockObservation.h>
#import "HKCommonDefine.h"
#import <objc/runtime.h>

@implementation UIView (KSShow)

- (NSString *)observerToken {
    return (NSString *)objc_getAssociatedObject(self, _cmd);
}

- (void)setObserverToken:(NSString *)token {
    objc_setAssociatedObject(self, @selector(observerToken), token, OBJC_ASSOCIATION_RETAIN);
}

- (void)ks_triggerRoundCorner {
    if (self.observerToken.length) {
        return;
    }
    self.layer.cornerRadius = self.bounds.size.height / 2.0;
    WS
    NSArray *keyPaths = @[@"frame", @"bounds"];
    self.observerToken = [self bk_addObserverForKeyPaths:keyPaths options:NSKeyValueObservingOptionNew task:^(id  _Nonnull obj, NSString * _Nonnull keyPath, NSDictionary * _Nonnull change) {
        SS
        if (fabs(self.layer.cornerRadius * 2 - self.bounds.size.height) >= 0.1) {
           self.layer.cornerRadius = self.bounds.size.height / 2.0;
        }
    }];
}

- (void)ks_triggerWidthRoundCorner {
    if (self.observerToken.length) {
        return;
    }
    self.layer.cornerRadius = self.bounds.size.width / 2.0;
    WS
    NSArray *keyPaths = @[@"frame", @"bounds"];
    self.observerToken = [self bk_addObserverForKeyPaths:keyPaths options:NSKeyValueObservingOptionNew task:^(id  _Nonnull obj, NSString * _Nonnull keyPath, NSDictionary * _Nonnull change) {
        SS
        if (fabs(self.layer.cornerRadius * 2 - self.bounds.size.width) >= 0.1) {
           self.layer.cornerRadius = self.bounds.size.width / 2.0;
        }
    }];
}

- (void)ks_unTriggerRoundCorner {
    if (self.observerToken) {
        [self bk_removeObserversWithIdentifier:self.observerToken];
        self.observerToken = nil;
    }
    
}


@end
